package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.BrandDTO;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl extends ServiceImpl <BrandMapper,Brand> implements BrandService {
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryBrandService categoryBrandService;


    /**
     * 根据品牌Id查询品牌
     * @param id
     * @return
     */
    @Override
    public BrandDTO queryBrandById(Long id) {
//        Brand byId = brandService.getById(id);
//        BrandDTO brandDTO = new BrandDTO(byId);
//        return brandDTO;
        return new BrandDTO(getById(id));
    }

    @Override
    public List<BrandDTO> queryBrandByIds(List<Long> idList) {
        List<Brand> brandList = brandService.listByIds(idList);
        return BrandDTO.convertEntityList(brandList);
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        //分页信息的健壮性处理
        Math.min(page,100);
        Math.max(rows,5);
        //分页
        Page<Brand> info = new Page<>(page, rows);
        //判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        //如果key存在，添加like和eq的查询方法 否则不添加
        query().like(isKeyExists,"name",key)
                .or()
                .eq(isKeyExists,"letter",key)
                .page(info);
        //封装结果
        List<Brand> list = info.getRecords();
        return new PageDTO<>(info.getTotal(),info.getPages(),BrandDTO.convertEntityList(list));
    }


//新增
    @Override
    @Transactional
    public void addBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存brand并回显id
        save(brand);
        //保存中间表
        saveCategoryBrand(brandDTO.getCategoryIds(),brand.getId());
    }

    private void saveCategoryBrand(List<Long> categoryIds, Long id) {
        List<CategoryBrand> categoryBrands = categoryIds
                .stream()
                .map(categoryId -> CategoryBrand.of(categoryId, id))
                .collect(Collectors.toList());

        this.categoryBrandService.saveBatch(categoryBrands);
    }
//修改
    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存brand并回显id
        updateById(brand);
        //清理之前中间表联系的关系
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",brand.getId()));
        //重建分类和品牌之间的信息
        saveCategoryBrand(brandDTO.getCategoryIds(),brand.getId());

    }
//删除
    @Override
    @Transactional
    public void deleteBrand(Long id) {
        //TODO 什么样的品牌才能被删除，不满足条件的一定不能删除（有人用）
        removeById(id);
        //根据id删除中间表信息
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",id));
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        List<Brand> list = getBaseMapper().queryByCategoryId(id);
        return BrandDTO.convertEntityList(list);
    }

}
